package com.obggtc.picture.service.ai.impl;

import com.obggtc.picture.config.TencentAiConfig;
import com.obggtc.picture.dto.ai.AiChatRequest;
import com.obggtc.picture.dto.ai.AiChatResponse;
import com.obggtc.picture.enums.AiProviderEnum;
import com.obggtc.picture.service.ai.AiProvider;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.hunyuan.v20230901.HunyuanClient;
import com.tencentcloudapi.hunyuan.v20230901.models.ChatCompletionsRequest;
import com.tencentcloudapi.hunyuan.v20230901.models.ChatCompletionsResponse;
import com.tencentcloudapi.hunyuan.v20230901.models.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 腾讯混元AI服务实现
 * 
 * @author system
 * @date 2025/09/29
 */
@Slf4j
@Service
public class TencentAiProvider implements AiProvider {
    
    @Autowired
    private TencentAiConfig tencentAiConfig;
    
    @Override
    public AiProviderEnum getProviderType() {
        return AiProviderEnum.TENCENT_HUNYUAN;
    }
    
    @Override
    public AiChatResponse chat(AiChatRequest request) {
        try {
            log.info("使用腾讯混元AI处理聊天请求，消息：{}", request.getMessage());
            
            // 参数校验
            if (request == null || !StringUtils.hasText(request.getMessage())) {
                return AiChatResponse.error("消息内容不能为空");
            }
            
            // 检查服务配置
            if (!isServiceAvailable()) {
                return AiChatResponse.error("腾讯AI服务配置不完整，请检查配置");
            }
            
            // 调用腾讯混元API
            String aiResponse = callHunyuanApi(request);
            
            if (StringUtils.hasText(aiResponse)) {
                AiChatResponse response = AiChatResponse.success(aiResponse, request.getSessionId());
                log.info("腾讯混元AI响应成功，会话ID：{}", request.getSessionId());
                return response;
            } else {
                return AiChatResponse.error("腾讯AI服务暂时不可用，请稍后再试");
            }
            
        } catch (Exception e) {
            log.error("腾讯混元AI聊天服务异常", e);
            return AiChatResponse.error("腾讯AI服务异常：" + e.getMessage());
        }
    }
    
    @Override
    public boolean isServiceAvailable() {
        return tencentAiConfig != null 
            && StringUtils.hasText(tencentAiConfig.getSecretId()) 
            && StringUtils.hasText(tencentAiConfig.getSecretKey())
            && StringUtils.hasText(tencentAiConfig.getRegion())
            && StringUtils.hasText(tencentAiConfig.getModel())
            && !tencentAiConfig.getSecretId().equals("your-secret-id")
            && !tencentAiConfig.getSecretKey().equals("your-secret-key");
    }
    
    @Override
    public boolean testConnection() {
        try {
            AiChatRequest testRequest = new AiChatRequest();
            testRequest.setMessage("测试连接");
            testRequest.setMaxTokens(10);
            
            AiChatResponse response = chat(testRequest);
            return response.getCode() == 200 && StringUtils.hasText(response.getContent());
        } catch (Exception e) {
            log.error("腾讯AI连接测试失败", e);
            return false;
        }
    }
    
    /**
     * 调用腾讯混元API
     * 
     * @param request 聊天请求
     * @return AI响应内容
     */
    private String callHunyuanApi(AiChatRequest request) {
        try {
            log.info("开始调用腾讯混元API，模型：{}", tencentAiConfig.getModel());
            
            // 创建认证信息
            Credential cred = new Credential(tencentAiConfig.getSecretId(), tencentAiConfig.getSecretKey());
            
            // 实例化HTTP选项
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("hunyuan.tencentcloudapi.com");
            httpProfile.setConnTimeout(tencentAiConfig.getTimeout() / 1000); // 转换为秒
            httpProfile.setReadTimeout(tencentAiConfig.getTimeout() / 1000);
            
            // 实例化客户端配置对象
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            
            // 实例化要请求产品的client对象
            HunyuanClient client = new HunyuanClient(cred, tencentAiConfig.getRegion(), clientProfile);
            
            // 实例化一个请求对象
            ChatCompletionsRequest apiRequest = new ChatCompletionsRequest();
            apiRequest.setModel(tencentAiConfig.getModel());
            
            // 构建消息数组
            Message[] messages = new Message[1];
            if (StringUtils.hasText(request.getSystemRole())) {
                messages = new Message[2];
                Message systemMessage = new Message();
                systemMessage.setRole("system");
                systemMessage.setContent(request.getSystemRole());
                messages[0] = systemMessage;
                
                Message userMessage = new Message();
                userMessage.setRole("user");
                userMessage.setContent(request.getMessage());
                messages[1] = userMessage;
            } else {
                Message userMessage = new Message();
                userMessage.setRole("user");
                userMessage.setContent(request.getMessage());
                messages[0] = userMessage;
            }
            
            apiRequest.setMessages(messages);
            
            // 设置其他参数
            if (request.getTemperature() != null) {
                apiRequest.setTemperature(request.getTemperature().floatValue());
            }
            
            log.info("发送请求到腾讯混元API，消息长度：{}", request.getMessage().length());
            
            // 返回的resp是一个ChatCompletionsResponse的实例，与请求对象对应
            ChatCompletionsResponse resp = client.ChatCompletions(apiRequest);
            
            // 处理响应
            if (resp.getChoices() != null && resp.getChoices().length > 0) {
                String content = resp.getChoices()[0].getMessage().getContent();
                log.info("腾讯混元API调用成功，响应长度：{}", content != null ? content.length() : 0);
                return content;
            } else {
                log.warn("腾讯混元API响应为空");
                return null;
            }
            
        } catch (TencentCloudSDKException e) {
            log.error("腾讯混元API调用异常", e);
            if (e.getMessage().contains("InvalidCredential")) {
                throw new RuntimeException("腾讯API密钥配置错误，请检查SecretId和SecretKey");
            } else if (e.getMessage().contains("QuotaLimitExceeded")) {
                throw new RuntimeException("腾讯API调用配额已用完，请检查账户余额");
            } else {
                throw new RuntimeException("腾讯混元API调用失败：" + e.getMessage());
            }
        } catch (Exception e) {
            log.error("调用腾讯混元API时发生未知异常", e);
            throw new RuntimeException("腾讯AI服务调用异常：" + e.getMessage());
        }
    }
}
